import { Button, Checkbox, Form, Input, notification } from "antd";
import React, { useState } from "react";
import { useNavigate, Link } from "react-router-dom";
import { _login } from "../../store/apis/adminApi";
import { useDispatch } from "react-redux";
import { login, logout } from "../../store/reducer/authSlice.js";

const Login = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();

  //表单成功提交方法
  const onFinish = async (values) => {
    const logdata = JSON.stringify(values);
    //通过封装的登录方法发送请求
    const res = await _login(logdata);
    // console.log(res);
    if (res.data.isSuccess) {
      //将登录信息存储到redux中
      dispatch(
        login({
          token: res.data.token,
        })
      );
      //跳转页面
      navigate("/home/summary_data",{ replace: true });
    } else {
      //返回登录页面
      navigate("/", { replace: true });
    }
  };

  return (
    <>
      <center>
        <h2>请使用您的账号密码登录系统</h2>
      </center>
      <Form
        name="basic"
        labelCol={{
          span: 8,
        }}
        wrapperCol={{
          span: 9,
        }}
        initialValues={{
          remember: true,
        }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="账号"
          name="adminaccount"
          rules={[
            {
              required: true,
              message: "请输入账号!",
            },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="密码"
          name="adminpwd"
          rules={[
            {
              required: true,
              message: "请输入密码!",
            },
          ]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item
          // name="remember"
          valuePropName="checked"
          wrapperCol={{
            offset: 8,
            span: 9,
          }}
        >
          <Checkbox>记住密码</Checkbox>
        </Form.Item>

        <Form.Item
          wrapperCol={{
            offset: 8,
            span: 9,
          }}
        >
          <Button type="primary" htmlType="submit">
            登录
          </Button>

          <Button style={{ marginLeft: "10px" }}>
            <Link to="/register">注册</Link>
          </Button>
        </Form.Item>
      </Form>
    </>
  );
};
export default Login;
